//
//  JCCUpdateUserInfoViewController.swift
//  剂查查
//
//  Created by xianquan on 2024/12/12.
//  Copyright © 2024 shipin. All rights reserved.
//

import CommonTools
import TYUIKit
import SDWebImage
import TYAlertView
import TZImagePickerController
import MobileCoreServices

class JCCUpdateUserInfoViewController: BaseViewController {
    
    var dataList: [ItemModel] = []
    
    let updateData = JCCManager.shared.user
    
    private let maxCount = 4
    
    private var selectedPhotos: [UIImage] = []
    
    private var selectedAssets: [PHAsset] = []
    
    private var isSelectOriginalPhoto = false
    
    private var imagePickerVc = UIImagePickerController()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .blackf6
        imagePickerVc.delegate = self
        setTitle("个人信息")
        configureTableView()
        setupData()

    }
    
    func setupData() {
        
        for type in ItemType.allCases {
            let item = ItemModel(type: type)
            dataList.append(item)
        }
        tableView.reloadData()
    }

    override func configureTableView() {
        self.configureTableView(with: .grouped)
        
        tableView.snp.makeConstraints { make in
            make.leading.equalTo(adapt(16))
            make.trailing.equalTo(adapt(-16))
            make.top.equalTo(TY_NaviBarHeight())
            make.bottom.equalTo(0)
        }
        tableView.backgroundColor = view.backgroundColor
        tableView.separatorStyle = .none
        tableView.xw_register(HeadCell.self)
        tableView.xw_register(InputCell.self)
        tableView.xw_register(CommonCell.self)
        tableView.xw_register(RemarkCell.self)
        
        let footerView = UIView(backgroundColor: .clear, in: nil, frame: CGRect(x: 0, y: 0, width: screenWidth(), height: 105))
        let saveBtn = UIButton(image: nil, title: "保存", titleColor: .white, font: 15.regular, in: footerView) {make in
            make.centerX.equalToSuperview()
            make.top.equalTo(55)
            make.width.equalTo(293)
            make.height.equalTo(50)
        }
        saveBtn.setBackgroundColor(UIColor(hex: "#2767E6"), for: .normal)
        saveBtn.cut(withRadius: 25)
        tableView.tableFooterView = footerView

        saveBtn.addBlock(for: .touchUpInside) {[unowned self] _ in
            if let photo = selectedPhotos.first {
                showLoading()
                JCCNet.uploadImage(image: photo) {[weak self] model, error in
                    if let model = model {
                        XWLog(value: "图片上传成功:\(model.result)")
                        if model.isSuccess {
                            if let dic = model.result as? [String: Any], let url = dic["url"] as? String {
                                self?.updateData.headimg = url
                                self?.saveInfo()
                            }
                        }
                        else {
                            toast(message: "图片上传失败")
                        }
                    }
                    else {
                        hideLoading()
                        XWLog(value: "图片上传失败")
                        toast(message: "图片上传失败")
                    }
                }
            }
            else {
                showLoading()
                saveInfo()
            }
        }
    }
    
    func saveInfo(){
        NetworkRequest.request(networkType: .updateUserInfo(headimg: updateData.headimg, realname: updateData.realname, age: updateData.age, gender: updateData.gender, remark: updateData.remark)) { result in
            hideLoading()
            switch result {
            case .success:
                XWLog(value: "更新成功")
                toast(message: "用户信息更新成功")
                JCCUser.loadUserInfo {
                    self.navigationController?.popViewController(animated: true)
                }
            case .failure(let error):
                XWLog(value: "更新失败：\(error)")
                toast(message: "用户信息更新失败")
            }
        }
    }

}

extension JCCUpdateUserInfoViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        1
    }
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        self.dataList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let data = self.dataList[indexPath.section]
        guard let cell = tableView.dequeueReusableCell(withIdentifier: data.cellIdentifier) else {return UITableViewCell()}
        cell.backgroundColor = .clear
        cell.selectionStyle = .none
        cell.contentView.backgroundColor = .white
        cell.contentView.layer.cornerRadius = 12
        if let cell = cell as? ShowUserInfoProtocol {
            cell.show(data: data)
        }
        if var cell = cell as? InputCallbackProtocol {
            cell.callback = {[unowned self] text in
                if data.type == .name {
                    updateData.realname = text
                }
                else if data.type == .remark {
                    updateData.remark = text
                }
                data.detail = text
            }
        }
        return cell
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        12
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let data = self.dataList[indexPath.section]
        if data.type == .remark {
            return 150
        }
        return 64
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let data = self.dataList[indexPath.section]
        if data.type == .icon {
            pickerImage()
//            XWWeChatOpenSDKBridgeProtocolImpl.shared.sendShareReq()
        }
        else if data.type == .gender {
            TYAlertView.showCommonAlert(message: nil, style: .actionSheet, buttonTitles: ["男", "女"], cancelButtonTitle: "取消") {[self] alert, index in
                data.detail = index == 1 ? "男" : "女"
                updateData.gender = index
                tableView.reloadData()
            }
        }
        else if data.type == .age {
            var arr: [String] = []
            for i in 10...100 {
                arr.append("\(i)")
            }
            TYAlertView.showCommonAlert(message: nil, style: .actionSheet, buttonTitles: arr, cancelButtonTitle: "取消") {[self] alert, index in
                let age = arr[index - 1]
                data.detail = age
                updateData.age = Int(age) ?? 0
                tableView.reloadData()
            }
        }
    }
}

extension JCCUpdateUserInfoViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate, TZImagePickerControllerDelegate {
    func pickerImage() {
        TYAlertView.showCommonAlert(message: nil, style: .actionSheet, buttonTitles: ["相机", "相册"], cancelButtonTitle: "取消") {[self] alert, index in
            if (index == 1) {
                imagePickerVc.sourceType = .camera
                imagePickerVc.mediaTypes = [kUTTypeImage as String] //["public.image"]
                TY_TopViewController().present(imagePickerVc, animated: true)
            }
            else if (index == 2) {
                if let imagePickerVc = TZImagePickerController(maxImagesCount: maxCount, columnNumber: 4, delegate: self, pushPhotoPickerVc: true) {
                    if !selectedAssets.isEmpty {
                        imagePickerVc.selectedAssets = NSMutableArray(array: selectedAssets)
                    }
                    imagePickerVc.allowTakeVideo = true
                    imagePickerVc.allowTakeVideo = false
                    imagePickerVc.iconThemeColor = .selectedColor
                    imagePickerVc.showPhotoCannotSelectLayer = true
                    imagePickerVc.cannotSelectLayerColor = UIColor(white: 1, alpha: 0.8)
                    imagePickerVc.allowPickingImage = true
                    imagePickerVc.allowPickingOriginalPhoto = true
                    imagePickerVc.sortAscendingByModificationDate = true
                    imagePickerVc.showSelectedIndex = true
                    imagePickerVc.didFinishPickingPhotosHandle = {[self] photos, assets, isSelectOriginalPhoto in
                        guard let photo = photos, let assets = assets as? [PHAsset] else {return}
                        updatePhotos(photo: photo, assets: assets)
                    }
                    imagePickerVc.modalPresentationStyle = .fullScreen
                    TY_TopViewController().present(imagePickerVc, animated: true)
                }
                
                
            }
        }
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true)
        let image = info[.originalImage] as? UIImage
        TZImageManager.default().savePhoto(with: image) {[self] asset, error in
            if let error = error {
                XWLog(value: "图片保存失败\(error)")
            }
            else {
                refreshCollectionView(asset: asset, image: image )
            }
        }
    }
    
    func refreshCollectionView(asset: PHAsset?, image: UIImage?){
        if let asset = asset {
            selectedAssets.append(asset)
        }
        if let image = image {
            selectedPhotos.append(image)
        }
        let data = self.dataList[0]
        data.iconImage = image
        tableView.reloadData()
    }
    
    func updatePhotos(photo: [UIImage], assets: [PHAsset]) {
        selectedPhotos = photo
        let data = self.dataList[0]
        data.iconImage = photo.first
        selectedAssets = assets
        tableView.reloadData()
    }
}


extension JCCUpdateUserInfoViewController {
    class HeadCell: UITableViewCell, ShowUserInfoProtocol {
        
        private lazy var titleLabel: UILabel = UILabel(font: 15.regular, textColor: .black3, in: contentView) {[unowned self] make in
            make.leading.equalTo(21)
            make.centerY.equalTo(contentView)
        }
        
        private lazy var icon = UIImageView(image: nil, in: contentView) { make in
            make.trailing.equalTo(-10)
            make.width.height.equalTo(44)
            make.centerY.equalToSuperview()
        }

        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            
            _ = titleLabel
            icon.cut(withRadius: 22)
            icon.backgroundColor = UIColor(hexString: "#D2EAFF")
            
            adaptScreen()
        }
        
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        func show(data: ItemModel) {
            titleLabel.text = data.title
            if let image = data.iconImage {
                icon.image = image
            }
            else {
                icon.sd_setImage(with: URL(string: data.icon), placeholderImage: UIImage(named: "icon_placeholder"))
            }
        }
    }
}


extension JCCUpdateUserInfoViewController {
    class CommonCell: UITableViewCell, ShowUserInfoProtocol {
        
        private lazy var titleLabel: UILabel = UILabel(font: 15.regular, textColor: .black3, in: contentView) {[unowned self] make in
            make.leading.equalTo(21)
            make.centerY.equalTo(contentView)
        }
        
        private lazy var detailInfoBtn: TYButton = {[unowned self] in
            let btn = TYButton(image: nil, title: nil, titleColor: .black3, font: 15.bold, in: contentView) {[unowned self] make in
                make.trailing.equalTo(-18)
                make.centerY.equalTo(contentView)
                make.height.equalTo(contentView)
                make.width.equalTo(150)
            }
            btn.ty_imageTitleSpace = 0
            btn.ty_imageLocation = .right
            btn.contentHorizontalAlignment = .right
            btn.isUserInteractionEnabled = false
            btn.setImage(UIImage(nameInBundle: .commonTools("app_back_black"))?.byRotate180()?.byResize(to: CGSize(width: 12, height: 11)), for: .normal)
            
            return btn
        }()

        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            
            _ = titleLabel
            _ = detailInfoBtn
            
            adaptScreen()
        }
        
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        func show(data: ItemModel) {
            titleLabel.text = data.title
            
            detailInfoBtn.setTitle(data.detail, for: .normal)
            
        }
    }
}

extension JCCUpdateUserInfoViewController {
    class InputCell: UITableViewCell, ShowUserInfoProtocol, InputCallbackProtocol {
        
        private lazy var titleLabel: UILabel = UILabel(font: 15.regular, textColor: .black3, in: contentView) {[unowned self] make in
            make.leading.equalTo(21)
            make.centerY.equalTo(contentView)
        }
        
        private lazy var tf = UITextField(font: 15.regular, textColor: .black3, text: "", placeholder: "请输入姓名", maxLength: 100, in: contentView) { make in
            make.centerY.height.equalToSuperview()
            make.trailing.equalTo(-10)
            make.width.equalTo(200)
        } _: {[unowned self] text in
            callback(text)
        }
        
        var callback: (String) -> () = {_ in}

        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            
            _ = titleLabel
            tf.textAlignment = .right
            
            adaptScreen()
        }
        
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        func show(data: ItemModel) {
            titleLabel.text = data.title
            
            tf.text = data.detail
            
        }
    }
}

extension JCCUpdateUserInfoViewController {
    class RemarkCell: UITableViewCell, UITextViewDelegate, ShowUserInfoProtocol, InputCallbackProtocol {
        
        var text: String = ""
        
        var tv: UITextView = UITextView()
        
        var callback: (String) -> () = {_ in}
        
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            let label = UILabel(font: 16.medium, textColor: .black3, in: contentView) { make in
                make.leading.top.equalTo(21)
                make.height.equalTo(20)
            }
            let att = NSMutableAttributedString(string: "个人签名")
            att.yy_font = 16.medium
            att.yy_color = .black3
            label.attributedText = att
            
            
            let tv = TYTextView(backgroundColor: .clear, in: contentView) { make in
                make.leading.equalTo(label)
                make.trailing.equalTo(-21)
                make.top.equalTo(label.snp.bottom).offset(14)
                make.bottom.equalTo(-14)
            }
            self.tv = tv
            tv.font = 16.regular
            let placeholder = NSMutableAttributedString(string: "请输入个人签名")
            placeholder.yy_font = adapt(16).regular
            placeholder.yy_color = UIColor(hexString: "#bebebe")
            tv.attributedPlaceholder = placeholder
            tv.delegate = self
        }
        
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        func textViewDidChange(_ textView: UITextView) {
            text = textView.text
            callback(text)
        }
        
        func show(data: ItemModel) {
//            titleLabel.text = data.title
            
            tv.text = data.detail
            
        }
    }
}


extension JCCUpdateUserInfoViewController {
    class ItemModel {
        var type: ItemType
        var title: String
        var detail: String
        var hasMore: Bool
        var icon: String
        var iconImage: UIImage?
        
        let cellIdentifier: String
        
        init(type: ItemType) {
            self.type = type
            self.title = type.rawValue
            self.detail = type.detail
            self.hasMore = type == .age || type == .gender
            self.icon = type == .icon ? JCCManager.shared.user.headimg : ""
            self.cellIdentifier = type.cellIdentifier
        }
    }
    
    enum ItemType: String, CaseIterable {
        case icon = "头像"
        case name = "姓名"
        case gender = "性别"
        case age = "年龄"
        case remark = "个人签名"
        
        var detail: String {
            let user = JCCManager.shared.user
            switch self {
            case .icon:
                return ""
            case .name:
                return user.realname
            case .gender:
                return user.gender > 0 ? (user.gender == 1 ? "男" : "女") : "未知"
            case .age:
                return "\(user.age)"
            case .remark:
                return user.remark
            }
        }
        
        var cellIdentifier: String {
            switch self {
            case .icon:
                return HeadCell.identifier
            case .name:
                return InputCell.identifier
            case .gender, .age:
                return CommonCell.identifier
            case .remark:
                return RemarkCell.identifier
            }
        }
    }
}

protocol ShowUserInfoProtocol {
    func show(data: JCCUpdateUserInfoViewController.ItemModel)
    
    
}

protocol InputCallbackProtocol {
    var callback: (String) -> () {get set}
}
